import { useState, useEffect } from 'react';
import request from '@/utils/request';

interface data {
  [as: string]: any;
}

// interface ReturnData {
//   data: data;
//   isLoading: boolean;
//   isError: boolean;
//   setQuery: (q: any) => void;
// }

const useData: any = (url: string, options = {}): any[] => {
  const [query, setQuery] = useState<any>({});
  const [data, setData] = useState<data>({});
  const [isLoading, setLoading] = useState<boolean>(false);
  const [isError, setError] = useState<boolean>(false);
  const [defaultList, setDefaultList] = useState<number>(1); //表示为列表进来得的还是触发了函数进来的
  useEffect(() => {
    async function fetchData() {
      try {
        if (url) {
          await request(url, {
            params: {
              pageIndex: 1,
              pageSize: 10,
              ...options,
              ...query,
            },
          }).then((res: any) => {
            if (res?.responseCode == 200) {
              const retData: any = res?.data;
              if (retData && retData.pagedItems && retData.pagedItems.length > 0) {
                retData.pagedItems.forEach((el: any, idx: number) => {
                  // 把返回的项都添加一个序号，用于在列表中显示
                  el.idx = (retData.current - 1) * retData.pageSize + (idx + 1);
                });
              }
              setData(retData);
            }
          });
        }
      } catch {
        setError(true);
      }
      setLoading(false);
    }
    setLoading(true);
    if (query.defalut) {
      setDefaultList(2);
      setQuery(() => ({
        ...query,
        defalut: undefined,
      }));
    } else {
      fetchData();
    }
  }, [url, query]);

  let returnData = [data, setQuery, isLoading, isError, defaultList];

  return returnData;
};

export default useData;
